<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <el-alert title="只允许为第三级分类设置相关参数" type="warning" :closable="false" show-icon></el-alert>

      <!-- 选择商品分类 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类:</span>
          <!-- 级联选择器 -->
          <el-cascader
            v-model="cateSelectKeys"
            :options="cateList"
            :props="cataProps"
            @change="handleCate"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏切换 -->
      <el-tabs v-model="activeName" @tab-click="tabChange">
        <!-- 动态参数的tab栏 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe style="width: 100%">
            <el-table-column align="center" type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="primary"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeParamsRight(index, scope.row,)"
                >{{item}}</el-tag>
                <!-- 渲染新增加的部分 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="#"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="动态参数"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 静态属性的tab栏 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled="isBtnDisabled" @click="addDialogVisible = true">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe style="width: 100%">
            <el-table-column align="center" type="expand">
              <template slot-scope="scope">
                <el-tag
                  type="success"
                  v-for="(item, index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="removeParamsRight(index, scope.row,)"
                >{{item}}</el-tag>
                <!-- 渲染新增加静态的部分 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  @close="removeParamsRight(i, scope.row,)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" type="index" label="#"></el-table-column>
            <el-table-column align="center" prop="attr_name" label="静态属性"></el-table-column>
            <el-table-column align="center" label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editParamsDialog(scope.row.attr_id)"
                >编辑</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeParams(scope.row.attr_id)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog
      :title="'添加' + titleText"
      :visible.sync="addDialogVisible"
      width="50%"
      @close="addParamsClear"
    >
      <!-- 表单区域 -->
      <el-form
        :model="addParamsForm"
        :rules="addParamsFormRules"
        ref="addParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑参数的对话框 -->
    <el-dialog
      :title="'修改' + titleText"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editParamsClear"
    >
      <!-- 表单区域 -->
      <el-form
        :model="editParamsForm"
        :rules="editParamsFormRules"
        ref="editParamsFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="editParamsForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {

      // 获取分类参数需要的数据
      cateList: [],

      // 定义可选择的数据配置
      cataProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        expandTrigger: 'hover'
      },

      // 定义级联选择器选中的值
      cateSelectKeys: [],

      // 定义tab栏默认值
      activeName: 'many',

      // 定义动态参数数据的数组
      manyTableData: [],

      // 定义静态参数的数据数组
      onlyTableData: [],

      // 控制对话框的显示和隐藏
      addDialogVisible: false,

      // 定义接收的数据的数组
      addParamsForm: {
        attr_name: ''
      },

      // 验证规则
      addParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 控制修改对话框的显示和隐藏
      editDialogVisible: false,

      // 修改动态参数和静态参数
      editParamsForm: {
        attr_name: ''
      },

      // 修改的验证规则
      editParamsFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },

      // 定义是否展示输入框
      inputVisible: false,

      // 定义双向绑定的input框输入的值
      inputValue: ''
    }
  },
  created () {
    this.getParamsList()
  },
  methods: {
    // 获取分类数据的方法
    async getParamsList () {
      const { data: res } = await this.$http.get('/categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cateList = res.data
      // console.log(this.cateList)
    },

    // 级联选择器变化 触发函数
    handleCate () {
      this.getParamsData()
    },

    // 点击切换tab栏
    tabChange () {
      this.getParamsData()
    },

    // 声明一个方法在级联选择器和tab栏切换时分别调用
    async getParamsData () {
      if (this.cateSelectKeys.length !== 3) {
        this.cateSelectKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return
      }
      // console.log(this.cateSelectKeys)
      // 获取数据 发送请求
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(',') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else {
        this.onlyTableData = res.data
      }
      // console.log(res.data)
    },
    // 关闭对话框 清空表单
    addParamsClear () {
      this.$refs.addParamsFormRef.resetFields()
    },

    // 点击确定 发送请求
    addParams () {
      this.$refs.addParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.addDialogVisible = false
      })
    },

    // 关闭修改对话框重置表单
    editParamsClear () {
      this.$refs.editParamsFormRef.resetFields()
    },

    // 点击编辑按钮 弹出对话框 并将后台的数据渲染到表单
    async editParamsDialog (attrId) {
      // console.log(attrId)
      const { data: res } = await this.$http.get(`/categories/${this.cateId}/attributes/${attrId}`, {
        params: { attr_sel: this.activeName }
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editParamsForm = res.data
      // this.getParamsData()
      // console.log(res.data)
      this.editDialogVisible = true
    },

    // 点击确定先进行预校验然后再发送请求
    editParams () {
      this.$refs.editParamsFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`/categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}`, {
          attr_name: this.editParamsForm.attr_name, attr_sel: this.editParamsForm.attr_sel
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.getParamsData()
        this.editDialogVisible = false
      })
    },

    // 点击删除按钮 删除
    async removeParams (attrId) {
      // console.log(attrId)
      const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult !== 'confirm') return this.$message.info('您取消了删除')
      const { data: res } = await this.$http.delete(`/categories/${this.cateId}/attributes/${attrId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getParamsData()
    },
    // 先抽取公共部分
    async saveParams (row) {
      const { data: res } = await this.$http.put(`/categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(',')
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
    },
    // tag中input框标签失去焦点或者按下enter触发的事件
    async handleInputConfirm (row) {
      // console.log(row)
      // 当鼠标离开输入框里面没有内容的时候清空 然后变回原来的初始化
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return false
      }
      // 如果没有return 证明里面由内容时候做下一步处理
      // 处理数组 并将数据push到数组 然后清空
      row.attr_vals.push(row.inputValue.trim())
      row.inputValue = ''
      row.inputVisible = false
      this.saveParams(row)
    },

    // 点击按钮是否展示输入框的事件
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // 点击标签叉号 删除参数
    removeParamsRight (index, row) {
      row.attr_vals.splice(index, 1)
      this.saveParams(row)
    }
  },
  computed: {
    // 添加一个计算属性绑定按钮
    isBtnDisabled () {
      if (this.cateSelectKeys.length !== 3) {
        return true
      } else {
        return false
      }
    },

    // 获取发送请求的id 当级联选择器的长度等于3 获取索引为2的值
    cateId () {
      if (this.cateSelectKeys.length === 3) {
        return this.cateSelectKeys[2]
      } else {
        return null
      }
    },

    // 添加一个绑定title的计算属性
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      }
      return '静态属性'
    }
  }
}
</script>

<style lang="less" scoped>
.cat-opt {
  margin: 20px 0;

  .el-cascader {
    margin-left: 10px;
  }
}
.el-tag {
  margin: 10px;
}
.input-new-tag {
  width: 125px;
}
</style>
